<script lang="ts" setup>
import type { FormKitFrameworkContext } from "@formkit/core";
import { IconImageAddLine, IconDeleteBin } from "@halo-dev/components";
import { ref, computed, onMounted, nextTick, type PropType } from "vue";

const props = defineProps({
  context: {
    type: Object as PropType<FormKitFrameworkContext>,
    required: true,
  },
});

const fileInput = ref<HTMLInputElement>();
const uploading = ref(false);
const mounted = ref(false);

// 检查是否支持多选
const isMultiple = computed(() => {
  // 检查多个可能的位置
  const attrMultiple = props.context.attrs?.multiple;
  const nodeMultiple = props.context.node?.props?.multiple;
  const propsMultiple = props.context.multiple;
  
  console.log('Multiple检查:', {
    attrs: attrMultiple,
    node: nodeMultiple, 
    props: propsMultiple,
    formName: props.context.node?.name
  }); // 调试信息
  
  // 临时强制启用多选模式进行测试
  if (props.context.node?.name === 'images') {
    return true;
  }
  
  return attrMultiple === true || attrMultiple === 'true' || attrMultiple === '' ||
         nodeMultiple === true || nodeMultiple === 'true' || nodeMultiple === '' ||
         propsMultiple === true || propsMultiple === 'true' || propsMultiple === '';
});

// 获取图片数组
const imageUrls = computed(() => {
  const value = props.context._value;
  if (!value) return [];
  
  // 确保总是返回数组
  const urls = Array.isArray(value) ? value : [value];
  return urls.filter(url => url && url.trim() !== '');
});

// 检查是否有图片
const hasImage = computed(() => {
  return imageUrls.value.length > 0;
});

// 获取正确的图片URL（带/upload前缀）
const getImageUrl = (url: string) => {
  if (!url) return '';
  
  // 如果URL已经是完整的URL（http/https开头），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  
  // 如果URL已经有/upload前缀，直接返回
  if (url.startsWith('/upload/')) {
    return url;
  }
  
  // 否则添加/upload前缀
  return `/upload/${url}`;
};

// 从URL获取文件名
const getFileNameFromUrl = (url: string): string => {
  if (!url) return '';
  const segments = url.split('/');
  return segments[segments.length - 1] || url;
};

// 处理输入变化
const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const value = target.value.trim();
  
  if (isMultiple.value) {
    // 多选模式：如果有值，添加到现有数组中；否则清空
    if (value) {
      const currentUrls = imageUrls.value;
      if (!currentUrls.includes(value)) {
        props.context.node.input([...currentUrls, value]);
      }
    }
  } else {
    // 单选模式：直接设置
    props.context.node.input(value ? [value] : []);
  }
  
  // 清空输入框
  target.value = '';
};

// 处理文件选择
const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;
  
  if (!files || files.length === 0) return;
  
  try {
    uploading.value = true;
    
    const uploadedUrls: string[] = [];
    const currentUrls = imageUrls.value;
    
    // 依次上传每个文件
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // 创建 FormData 上传文件
      const formData = new FormData();
      formData.append('file', file);
      
      try {
        // 添加策略名称（后台管理需要）
        formData.append('policyName', 'default-policy');
        
        // 上传文件到服务器 - 使用控制台API而不是用户中心API
        const response = await fetch('/apis/api.console.halo.run/v1alpha1/attachments/upload', {
          method: 'POST',
          body: formData,
          credentials: 'include' // 包含认证信息
        });
        
        if (!response.ok) {
          throw new Error(`文件 ${file.name} 上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        console.log('上传结果:', result);
        
        // 获取上传后的URL
        let imageUrl: string | undefined;
        if (result.status?.permalink) {
          imageUrl = result.status.permalink;
        } else if (result.spec?.displayName) {
          imageUrl = result.spec.displayName;
        } else if (result.url) {
          imageUrl = result.url;
        }
        
        if (imageUrl) {
          uploadedUrls.push(imageUrl);
        } else {
          throw new Error(`文件 ${file.name} 服务器返回的数据中没有找到图片URL`);
        }
        
      } catch (error) {
        console.error(`文件 ${file.name} 上传失败:`, error);
        alert(`文件 ${file.name} 上传失败: ` + (error as Error).message);
      }
    }
    
    // 更新值
    if (uploadedUrls.length > 0) {
      if (isMultiple.value) {
        // 多选模式：合并到现有数组
        props.context.node.input([...currentUrls, ...uploadedUrls]);
      } else {
        // 单选模式：只保留最后一个
        props.context.node.input([uploadedUrls[uploadedUrls.length - 1]]);
      }
    }
    
  } catch (error) {
    console.error('文件上传失败:', error);
    alert('文件上传失败: ' + (error as Error).message);
  } finally {
    uploading.value = false;
    if (target) target.value = '';
  }
};

// 触发文件选择
const triggerFileSelect = () => {
  fileInput.value?.click();
};

// 移除所有图片
const removeAllImages = () => {
  props.context.node.input([]);
};

// 移除单个图片
const removeImage = (indexOrUrl: number | string) => {
  const currentUrls = imageUrls.value;
  
  if (typeof indexOrUrl === 'number') {
    // 按索引删除
    const newUrls = currentUrls.filter((_, index) => index !== indexOrUrl);
    props.context.node.input(newUrls);
  } else {
    // 按URL删除
    const newUrls = currentUrls.filter(url => url !== indexOrUrl);
    props.context.node.input(newUrls);
  }
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement;
  if (target) {
    target.style.display = 'none';
  }
};

// 组件挂载后创建额外内容的容器
onMounted(() => {
  nextTick(() => {
    // 先检查容器是否已存在
    const existingContainer = document.getElementById(`${props.context.id}-extra-content`);
    if (existingContainer) {
      mounted.value = true;
      return;
    }
    
    // 找到FormKit的outer容器
    const element = document.getElementById(props.context.id);
    console.log('Found input element:', element); // 调试信息
    
    // 尝试多种选择器找到合适的容器
    let targetElement = element?.closest('[data-type="attachment"]') || 
                       element?.closest('.formkit-outer') || 
                       element?.parentElement?.parentElement;
    
    console.log('Found target element:', targetElement); // 调试信息
    
    if (targetElement && targetElement.parentNode) {
      // 创建额外内容的容器
      const extraContainer = document.createElement('div');
      extraContainer.id = `${props.context.id}-extra-content`;
      extraContainer.className = 'attachment-extra-content';
      
      // 插入到目标元素之后
      targetElement.parentNode.insertBefore(extraContainer, targetElement.nextSibling);
      console.log('Created extra container:', extraContainer); // 调试信息
    } else {
      console.warn('Could not find suitable target element for extra content container');
      // 如果找不到合适的容器，创建一个临时的body级别容器
      const bodyContainer = document.createElement('div');
      bodyContainer.id = `${props.context.id}-extra-content`;
      bodyContainer.className = 'attachment-extra-content';
      document.body.appendChild(bodyContainer);
    }
    
    mounted.value = true;
  });
});
</script>

<template>
  <!-- 只在formkit-inner中放置基本的输入框 -->
  <div class="relative">
    <input
      :id="context.id"
      :value="isMultiple ? '' : (Array.isArray(context._value) ? (context._value[0] || '') : (context._value || ''))"
      :class="context.classes.input"
      :name="context.node.name"
      v-bind="context.attrs"
      type="text"
      :placeholder="isMultiple ? '输入图片URL添加到列表中，或点击按钮选择多个文件' : '请输入图片URL，或点击按钮选择文件'"
      style="padding-right: 80px; min-height: 40px;"
      @input="handleInput"
      @blur="context.handlers.blur()"
    />
    
    <!-- 上传按钮 -->
    <div class="absolute right-2 top-1/2 -translate-y-1/2 flex gap-1">
      <button
        type="button"
        :disabled="uploading"
        @click="triggerFileSelect"
        class="flex items-center justify-center w-9 h-9 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors"
        title="选择文件"
      >
        <IconImageAddLine class="w-5 h-5" />
      </button>
      
      <button
        v-if="hasImage"
        type="button"
        @click="removeAllImages"
        class="flex items-center justify-center w-9 h-9 text-red-500 hover:text-red-700 hover:bg-red-50 rounded transition-colors"
        title="清除所有"
      >
        <IconDeleteBin class="w-5 h-5" />
      </button>
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      :multiple="isMultiple"
      class="hidden"
      @change="handleFileSelect"
    />
  </div>

  <!-- 临时调试：直接显示额外内容以确认逻辑正确 -->
  <div class="attachment-preview-debug" style="position: absolute; z-index: 9999; top: 100%; left: 0; width: 100%; background: white; border: 1px solid #ccc; margin-top: 5px;">
    <!-- 图片预览 -->
    <div v-if="hasImage" class="mt-4 p-3 bg-gray-50 rounded-lg border border-gray-200">
      <div class="space-y-3">
        <div v-for="(url, index) in imageUrls" :key="url" class="flex items-center space-x-4">
          <div class="relative flex-shrink-0">
            <div class="w-16 h-16 overflow-hidden rounded-lg border border-gray-300 bg-white shadow-sm">
              <img
                :src="getImageUrl(url)"
                alt="预览图片"
                class="w-full h-full object-cover"
                @error="handleImageError"
              />
            </div>
            <!-- 单个删除按钮 -->
            <button
              type="button"
              @click="removeImage(index)"
              class="absolute -top-1 -right-1 flex items-center justify-center w-5 h-5 bg-red-500 text-white rounded-full text-xs hover:bg-red-600 transition-colors"
              title="删除此图片"
            >
              ×
            </button>
          </div>
          <div class="flex-1 min-w-0 py-2">
            <div class="text-sm font-medium text-gray-900 truncate mb-1">
              {{ getFileNameFromUrl(getImageUrl(url)) }}
            </div>
            <div class="text-xs text-gray-500">
              图片 {{ index + 1 }} / {{ imageUrls.length }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传状态提示 -->
    <div v-if="uploading" class="mt-3 p-2 bg-blue-50 border border-blue-200 rounded-md">
      <div class="flex items-center">
        <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
        <span class="text-sm text-blue-700">正在处理文件...</span>
      </div>
    </div>

    <!-- 帮助文本 -->
    <div v-if="!hasImage && !uploading" class="mt-3 p-2 bg-gray-50 border border-gray-200 rounded-md">
      <div class="flex items-center text-xs text-gray-600">
        <IconImageAddLine class="w-4 h-4 mr-1 text-gray-500" />
        {{ isMultiple ? '支持多选图片：可输入图片URL或选择多个本地文件' : '支持直接输入图片URL，或点击按钮选择本地文件' }}
      </div>
    </div>
    
    <!-- 调试信息 -->
    <div class="p-2 text-xs text-gray-500 border-t">
      Debug - hasImage: {{ hasImage }}, multiple: {{ isMultiple }}, count: {{ imageUrls.length }}, uploading: {{ uploading }}
    </div>
  </div>

  <!-- 将额外内容通过Teleport移动到formkit-outer之外 -->
  <Teleport :to="`#${context.id}-extra-content`" v-if="mounted">
    <!-- 图片预览 -->
    <div v-if="hasImage" class="mt-4 p-3 bg-gray-50 rounded-lg border border-gray-200">
      <div class="space-y-3">
        <div v-for="(url, index) in imageUrls" :key="url" class="flex items-center space-x-4">
          <div class="relative flex-shrink-0">
            <div class="w-16 h-16 overflow-hidden rounded-lg border border-gray-300 bg-white shadow-sm">
              <img
                :src="getImageUrl(url)"
                alt="预览图片"
                class="w-full h-full object-cover"
                @error="handleImageError"
              />
            </div>
            <!-- 单个删除按钮 -->
            <button
              type="button"
              @click="removeImage(index)"
              class="absolute -top-1 -right-1 flex items-center justify-center w-5 h-5 bg-red-500 text-white rounded-full text-xs hover:bg-red-600 transition-colors"
              title="删除此图片"
            >
              ×
            </button>
          </div>
          <div class="flex-1 min-w-0 py-2">
            <div class="text-sm font-medium text-gray-900 truncate mb-1">
              {{ getFileNameFromUrl(getImageUrl(url)) }}
            </div>
            <div class="text-xs text-gray-500">
              图片 {{ index + 1 }} / {{ imageUrls.length }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传状态提示 -->
    <div v-if="uploading" class="mt-3 p-2 bg-blue-50 border border-blue-200 rounded-md">
      <div class="flex items-center">
        <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
        <span class="text-sm text-blue-700">正在处理文件...</span>
      </div>
    </div>

    <!-- 帮助文本 -->
    <div v-if="!hasImage && !uploading" class="mt-3 p-2 bg-gray-50 border border-gray-200 rounded-md">
      <div class="flex items-center text-xs text-gray-600">
        <IconImageAddLine class="w-4 h-4 mr-1 text-gray-500" />
        {{ isMultiple ? '支持多选图片：可输入图片URL或选择多个本地文件' : '支持直接输入图片URL，或点击按钮选择本地文件' }}
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
/* 只需要确保输入框本身有合适的样式 */
.relative {
  position: relative;
}

/* 额外内容容器的全局样式 */
:global(.attachment-extra-content) {
  margin-top: 0 !important;
}
</style>
